package assg.funnycells.util;

import java.io.*;

/* correct impl

public class RateLimPrintWriter extends PrintWriter {
    long timeout;
    long lastmove;
    Logger logger;

    public RateLimPrintWriter(OutputStream out, long timeout) {
	super(out);
	lastmove = System.currentTimeMillis();
	this.timeout = timeout;
	logger = Logger.getDefaultLogger();
    }

    public void println(String str) {
	// slow down movement
	if(str.indexOf("\n") != -1) {
	    String[] strs = str.split("\n", -1);
	    for(String s: strs)
		this.println(s);
	    return;
	}
	long currtime = System.currentTimeMillis();
	if(str.startsWith(assg.funnycells.server.Cell.MOVECELL) && currtime - lastmove < timeout)
	    try { Thread.sleep(timeout - currtime + lastmove); } catch(Exception e) { }
	super.println(str);
	lastmove = currtime;
    }
}

*/

public class RateLimPrintWriter extends PrintWriter {
    boolean newPacket;
    long timeout;
    Logger logger;

    public RateLimPrintWriter(OutputStream out, long timeout) {
        super(out);
        newPacket = true;
        this.timeout = timeout;
        logger = Logger.getDefaultLogger();
    }

    public void println(String str) {
        // slow down movement
        if(str.indexOf("\n") != -1) {
            String[] strs = str.split("\n", -1);
            for(String s: strs)
                this.println(s);
            return;
        }
        if(newPacket && str.startsWith(assg.funnycells.server.Cell.MOVECELL))
            try { Thread.sleep(timeout); } catch(Exception e) { }
        super.println(str);
        if(str.equals("")) {
            newPacket = true;
	    super.flush();
        } else {
            newPacket = false;
	}
    }
}

